<template>
  <el-row justify="space-between">
    <CompanySelector width="w-100" v-model="companyId"/>
    <el-button v-if="checkPermission(Permissions.department, Action.add)" type="primary"
               @click="addDepartmentDialog=true">添加部门
    </el-button>
  </el-row>
  <el-divider/>
  <el-table :data="departments" v-loading="isLoading" stripe border table-layout="auto">
    <el-table-column label="公司ID" prop="gs_id"></el-table-column>
    <el-table-column label="部门ID" prop="id"></el-table-column>
    <el-table-column label="部门名称" prop="name"></el-table-column>
    <el-table-column label="部门路径" prop="path"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-popconfirm
            v-if="checkPermission(Permissions.department, Action.delete)"
            class="box-item"
            :title="'确定删除' + scope.row.name + '吗？'"
            placement="top-start"
            @confirm="deleteDepartmentFn(scope.row.id)"
        >
          <template #reference>
            <el-button type="danger" :disabled="deleteLoading" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <add-department-dialog v-model="addDepartmentDialog" @success="refetch"/>
</template>

<script setup lang="ts">
import {useMutation, useQuery} from "@pinia/colada";
import {deleteDepartment, getDepartments} from "../../api/department.ts";
import CompanySelector from "../../components/CompanySelector.vue";
import {ref} from "vue";
import AddDepartmentDialog from "./components/AddDepartmentDialog.vue";
import {ElMessage} from "element-plus"
import {useUserStore} from "../../store/userStore.ts";
import {Action, Permissions} from "../../types/permissions.ts";

const companyId = ref<number>()
const addDepartmentDialog = ref(false)

let {checkPermission} = useUserStore();

let {data: departments, isLoading, refetch} = useQuery({
  key: () => ["company's", companyId.value ?? null],
  query: () => getDepartments(companyId),
  enabled: () => companyId.value !== undefined
});

let {mutate: deleteDepartmentFn, isLoading: deleteLoading} = useMutation({
  mutation: (departmentId: number) => deleteDepartment(departmentId),
  onSuccess: () => {
    refetch()
    ElMessage.success("删除成功")
  },
  onError: () => {
    ElMessage.error("删除失败")
  }
});
</script>

<style scoped>

</style>